package com.elite.groovy.callback



import com.elite.groovy.util.EliteBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.elite.groovy.util.Util;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;

/**
 *
 * @author luper
 *
 */


public  class CreateVAS implements ServiceBackInvoke{
    public static final Log log = LogFactory.getLog(CreateVAS.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response){
        log.debug("-----Begin Systeam----------");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String requestJSONStr =Util.getRequestBody(request, "UTF-8");
		
		try{
		
			//解析请求json
			JSONObject json  = new JSONObject().fromObject(requestJSONStr);
			//获取请求type
			String v_interfacetype;
			if(json.has("interfaceType")){
				v_interfacetype = json.getString("interfaceType");
			}else{
				//返回失败结果
				JSONObject  responseJson = new JSONObject();
				responseJson.put("retCode", "-1");
				responseJson.put("retMessage", "未识别到type参数");
				return responseJson;
			}
			//记录请求内容
			eliteBean.update("insert into INTERFACE_JSONBODY values(sysdate,'gwfk','CreateVAS','"+requestJSONStr.toString()+"',sysdate,null)","dataSource");
		
		
		
			//同步增值服务订单数据
			if(v_interfacetype=="create"){
				String orderNo  = json.getString("orderNo");        		//增值服务平台订单号
				String ibcallname = json.getString("ibCallName");               //来电人姓名
				String ibcalltel = json.getString("ibCallTel");     //来电人电话
				String callstarttime = json.getString("callStartTime");       	  		//来电时间
				String callby = json.getString("callBy");        			//联系人姓名
				String calltel = json.getString("callTel");      				//联系电话
				String item_id  = json.getString("itemId");        		//服务项目id
				String item_name  = json.getString("itemName");        		//服务项目名称
				String service_type  = json.getString("serviceType");        		//服务类型id
				String service_type_name  = json.getString("serviceTypeName");        		//服务类型名称
				String supplier_id  = json.getString("supplierId");        		//服务商id
				String supplier_name  = json.getString("supplierName");        		//服务商名称	
				String vas_source = json.getString("source");					//下单来源   1-坐席下单，2-官微下单
				String source = "";
				if(vas_source=="2"){
					source = "VAS_INTERFACE"	//增值平台-官微下单
				}else{
					source = "VAS_AGENT"		//增值平台-人工下单
				}
				String policyno = "";
				if(json.has("policyNo")){
					policyno = json.getString("policyNo");
				}
				String province = "";
				if(json.has("province")){
					province  = json.getString("province");        		//救援地址省id
				}
				String province_name  = "";
				if(json.has("province_name")){
					province_name  = json.getString("provinceName");      //救援地址省名称
				}
				String city  = "";
				if(json.has("city")){
					city  = json.getString("city");        		//救援地址市id
				}
				String city_name  = "";
				if(json.has("city_name")){
					city_name  = json.getString("cityName");        		//救援地址市名称
				}
				String area  = "";
				if(json.has("area")){
					area  = json.getString("area");        		//救援地址区id
				}
				String area_name  = "";
				if(json.has("area_name")){
					area_name  = json.getString("areaName");        		//救援地址区名称
				}
				String address  = "";
				if(json.has("address")){
					address  = json.getString("address");        		//救援地址详细位置
				}
				String licenseNo = "";
				if(json.has("licenseNo")){
					licenseNo = json.getString("licenseNo");  			//车牌
				}
				String frameNo = "";
				if(json.has("frameNo")){
					frameNo = json.getString("frameNo");  				//车架号
				}
				String engineNo = "";
				if(json.has("engineNo")){
					engineNo = json.getString("engineNo");  				//发动机号
				}
				String coverageName = "";
				if(json.has("coverageName")){
					coverageName = json.getString("coverageName");  		//险种
				}
				String brandName = "";
				if(json.has("brandName")){
					brandName = json.getString("brandName");  			//车型
				}
				String carAge = "";
				if(json.has("carAge")){
					carAge = json.getString("carAge");  					//车辆初登日期
				}
				String seatNum = "";
				if(json.has("seatNum")){
					seatNum = json.getString("seatNum");  				//座位数
				}
				String reNewInsuranceFlag = "";
				if(json.has("reNewInsuranceFlag")){
					reNewInsuranceFlag = json.getString("reNewInsuranceFlag");  			//续保客户标识
				}
				String isNWEmployee = "";
				if(json.has("isNWEmployee")){
					isNWEmployee = json.getString("isNWEmployee");  			//南网客户标识
				}
				String insured = "";
				if(json.has("insured")){
					insured = json.getString("insured");  				//被保人
				}
				String organiza = "";
				if(json.has("organiza")){
					organiza = json.getString("organiza");  				//二级机构代码
				}
				String organizaName = "";
				if(json.has("organizaName")){
					organizaName = json.getString("organizaName");  			//二级机构名称
				}
				
				String riskcode;
				if(item_id=="01"){
					riskcode="RS";
				}else if(item_id=="03"){
					riskcode="VS";
				}else if(item_id=="04"){
					riskcode="DS";
				}else if(item_id=="05"){
					riskcode="DC";
				}else{
					riskcode="";
				}
				
				String destination;
				if(service_type=="0401"&&json.has("destination")){
					destination  = json.getString("destination");        		//目的地
				}else{
					destination="";
				}
				String order_remark  ="";
				if(json.has("order_remark")){
					order_remark  = json.getString("remark");        		//备注
				}
				String mileage;
				if(service_type=="0401"&&json.has("mileage")){
					mileage  = json.getString("mileage");        		//里程权益
				}else{
					mileage="";
				}
							
				int checkage=0;//只有服务类型是待办年检的才有车检年限
				if(service_type=="0501"){
				   checkage=2;
				}
				
				
				//生成objective_guid  工单号
				def querysql11="select sysguid objective_guid,'RCZZ'||to_char(sysdate,'YYYYMMDDhh24mi')||(case when SEQ_GWZTSORDER.nextval>=1 and SEQ_GWZTSORDER.nextval<10 then '000'||SEQ_GWZTSORDER.nextval  when SEQ_GWZTSORDER.nextval>=10 and SEQ_GWZTSORDER.nextval<100  then '00'||SEQ_GWZTSORDER.nextval  when SEQ_GWZTSORDER.nextval>=100 and SEQ_GWZTSORDER.nextval<1000  then '0'||SEQ_GWZTSORDER.nextval else to_char(SEQ_GWZTSORDER.nextval)end) workorderid from dual";
				def list11=eliteBean.chaxun_sql(querysql11,"dataSource");
				log.debug("list11-------------------------------"+list11);
				def map11=list11[0];
				log.debug("map11-------------------------------"+map11);
				def v_objective_guid=map11.get("objective_guid");
				def v_workorderid=orderNo;
				
				
				//新老客户检查
				def querysql1="select count(*) count1 from customer where customername='"+ibcallname+"' and mobile='"+ibcalltel+"'";
				def list1=eliteBean.chaxun_sql(querysql1,"dataSource");
				log.debug("list-------------------------------"+list1);
				for(def k=0;k<list1.size();k++){
					def map1=list1[k];
					def v_count1=map1.get("count1");
					log.debug("v_count1---v_count1-----v_count1----"+v_count1);

					//新客户新建准投诉
					if(v_count1==0){
						//新customer_guid
						def querysql2="select sysguid new_customer_guid from dual";
						def list2=eliteBean.chaxun_sql(querysql2,"dataSource");
						log.debug("list2-------------------------------"+list2);
						def map2=list2[0];
						log.debug("map2-------------------------------"+map2);
						def v_customer_guid=map2.get("new_customer_guid");
						log.debug("v_customer_guid-------------------------------"+v_customer_guid);

						//生成 customer
						def updatesql3="insert into customer(CUSTOMER_GUID,customertype_id,CUSTOMERNAME,MOBILE,WORKSTATUS)select '"+v_customer_guid+"','ZZjoin','"+ibcallname+"','"+ibcalltel+"','ONLINE'  FROM dual";
						def updatesqlresult3=eliteBean.update(updatesql3,"dataSource");
						log.debug("updatesqlresult3:"+updatesqlresult3);

						//生成 objective，realvisiter_flag表示暂不生成回访
						//SOURCE = 'INTERFACE'  官微下单  ,   SOURCE='VAS'  增值服务平台下单  ,   SOURCE="VAS_INTERFACE"     增值平台-官微下单, SOURCE="VAS_INTERFACE"    增值平台-人工下单
						def updatesql4="insert into objective(OBJECTIVE_GUID, OBJECTIVETYPE_ID,HANDLEGROUP_ID,PRIORITY_ID, EXPIREDDATE, CUSTOMER_GUID,OBJECTIVESTATUS,CREATEDBY, CREATEDDATE,WORKORDERFRAME_ID,CATEGORY,OBJECTIVESUBSTATUS,MAP_ID,CURSTEP_ID_MAP,QA_FLAG,ibcallname,ibcalltel,POLICYNO,CARNO,REOPEN,workorderid,SOURCE,ispolicy,callby,calltel,handlerole_id,frameno,engineno,riskcode,coverage_name,brandname,carage,seatnum,renewinsuranceflag,isnwemployee,insured,organizaname,organiza,realvisiter_flag,callstarttime)values('"+v_objective_guid+"','UR6GQO',null,'NORMAL',sysdate+5,'"+v_customer_guid+"','OPEN','kfstem',sysdate,'HWYY20','WORDER',null,'HWYY20','KC17US','0','"+ibcallname+"','"+ibcalltel+"','"+policyno+"','"+licenseNo+"','0','"+v_workorderid+"','"+source+"','1','"+callby+"','"+calltel+"','2LWZ8C','"+frameNo+"','"+engineNo+"','"+riskcode+"','"+coverageName+"','"+brandName+"','"+carAge+"','"+seatNum+"','"+reNewInsuranceFlag+"','"+isNWEmployee+"','"+insured+"','"+organizaName+"','"+organiza+"',9,'"+callstarttime+"')";
						def updatesqlresult4=eliteBean.update(updatesql4,"dataSource");
						log.debug("updatesqlresult4:"+updatesqlresult4);

						//生成 elitetask
						def updatesql5="insert into elitetask(ELITETASK_GUID,OBJECTIVE_GUID,OBJECTIVETYPE_ID,EXPECTSTARTTIME,EXPECTENDTIME,PRIORITY,HANDLEGROUP_ID,CUSTOMER_GUID,CURSTEPSTATUS,STEPFORECASTDATE,CURSTEP_ID_MAP, MAP_ID, OBJECTIVESUBSTATUS,OBFLAG,handlerole_id)values(sysguid,'"+v_objective_guid+"','UR6GQO',sysdate,sysdate,'NORMAL',null,'"+v_customer_guid+"','OPEN',sysdate,'KC17US','HWYY20',null,'0','2LWZ8C')";
						def updatesqlresult5=eliteBean.update(updatesql5,"dataSource");
						log.debug("updatesqlresult5:"+updatesqlresult5);

						//生成 tabc
						def updatesql6="insert into tabcdh_vas_list(RELATION_ID,schedul_type,province,province_name,city,city_name, area, area_name,address,item_id,item_name,service_type,service_type_name,supplier_id,supplier_name,checkage,destination,order_remark,mileage,dd_caseid,order_id,create_time)values('"+v_objective_guid+"',2,'"+province+"','"+province_name+"','"+city+"','"+city_name+"','"+area+"','"+area_name+"','"+address+"','"+item_name+"','"+item_name+"','"+service_type+"','"+service_type_name+"','"+supplier_id+"','"+supplier_name+"','"+checkage+"','"+destination+"','"+order_remark+"','"+mileage+"','"+orderNo+"','"+v_workorderid+"',sysdate)";
						def updatesqlresult6=eliteBean.update(updatesql6,"dataSource");
						log.debug("updatesqlresult6:"+updatesqlresult6);

						//返回成功结果
						JSONObject  jsonALL3 = new JSONObject();
						jsonALL3.put("retCode", "1");
						jsonALL3.put("retMessage", "success");
						jsonALL3.put("Workorderid", v_workorderid);
						return jsonALL3;
					}

					//老客户新建准投诉
					if(v_count1>0){

						//查已有的customer_guid
						def querysql7="select customer_guid customer_guid from customer where customername='"+ibcallname+"' and mobile='"+ibcalltel+"' and rownum=1";
						def list7=eliteBean.chaxun_sql(querysql7,"dataSource");
						log.debug("list7-------------------------------"+list7);
						def map7=list7[0];
						log.debug("map7-------------------------------"+map7);
						def v_customer_guid=map7.get("customer_guid");
						log.debug("v_customer_guid-------------------------------"+v_customer_guid);

						//更新 customer 的邮箱和所在地信息
						//def updatesql28="update customer set e_mail='"+v_email+"',address='"+v_address+"' where customer_guid='"+v_customer_guid+"'";
						//def updatesqlresult28=eliteBean.update(updatesql28,"dataSource");
						//log.debug("updatesqlresult28:"+updatesqlresult28);


						//生成 objective，realvisiter_flag表示暂不生成回访
						//SOURCE = 'INTERFACE'  官微下单  ,   SOURCE='VAS'  增值服务平台下单 ,   SOURCE="VAS_INTERFACE"     增值平台-官微下单, SOURCE="VAS_INTERFACE"    增值平台-人工下单
						def updatesql8="insert into objective(OBJECTIVE_GUID, OBJECTIVETYPE_ID,HANDLEGROUP_ID,PRIORITY_ID, EXPIREDDATE, CUSTOMER_GUID,OBJECTIVESTATUS,CREATEDBY, CREATEDDATE,WORKORDERFRAME_ID,CATEGORY,OBJECTIVESUBSTATUS,MAP_ID,CURSTEP_ID_MAP,QA_FLAG,ibcallname,ibcalltel,POLICYNO,CARNO,REOPEN,workorderid,SOURCE,ispolicy,callby,calltel,handlerole_id,frameno,engineno,riskcode,coverage_name,brandname,carage,seatnum,renewinsuranceflag,isnwemployee,insured,organizaname,organiza,realvisiter_flag,callstarttime)values('"+v_objective_guid+"','UR6GQO',null,'NORMAL',sysdate+5,'"+v_customer_guid+"','OPEN','kfstem',sysdate,'HWYY20','WORDER',null,'HWYY20','KC17US','0','"+ibcallname+"','"+ibcalltel+"','"+policyno+"','"+licenseNo+"','0','"+v_workorderid+"','"+source+"','1','"+callby+"','"+calltel+"','2LWZ8C','"+frameNo+"','"+engineNo+"','"+riskcode+"','"+coverageName+"','"+brandName+"','"+carAge+"','"+seatNum+"','"+reNewInsuranceFlag+"','"+isNWEmployee+"','"+insured+"','"+organizaName+"','"+organiza+"',9,'"+callstarttime+"')";
						def updatesqlresult8=eliteBean.update(updatesql8,"dataSource");
						log.debug("updatesqlresult8:"+updatesqlresult8);

						//生成 elitetask
						def updatesql9="insert into elitetask(ELITETASK_GUID,OBJECTIVE_GUID,OBJECTIVETYPE_ID,EXPECTSTARTTIME,EXPECTENDTIME,PRIORITY,HANDLEGROUP_ID,CUSTOMER_GUID,CURSTEPSTATUS,STEPFORECASTDATE,CURSTEP_ID_MAP, MAP_ID, OBJECTIVESUBSTATUS,OBFLAG,handlerole_id)values(sysguid,'"+v_objective_guid+"','UR6GQO',sysdate,sysdate,'NORMAL',null,'"+v_customer_guid+"','OPEN',sysdate,'KC17US','HWYY20',null,'0','2LWZ8C')";
						def updatesqlresult9=eliteBean.update(updatesql9,"dataSource");
						log.debug("updatesqlresult9:"+updatesqlresult9);

						//生成 tabc
						def updatesql10="insert into tabcdh_vas_list(RELATION_ID,schedul_type,province,province_name,city,city_name, area, area_name,address,item_id,item_name,service_type,service_type_name,supplier_id,supplier_name,checkage,destination,order_remark,mileage,dd_caseid,order_id,create_time)values('"+v_objective_guid+"',2,'"+province+"','"+province_name+"','"+city+"','"+city_name+"','"+area+"','"+area_name+"','"+address+"','"+item_name+"','"+item_name+"','"+service_type+"','"+service_type_name+"','"+supplier_id+"','"+supplier_name+"','"+checkage+"','"+destination+"','"+order_remark+"','"+mileage+"','"+orderNo+"','"+v_workorderid+"',sysdate)";
						def updatesqlresult10=eliteBean.update(updatesql10,"dataSource");
						log.debug("updatesqlresult10:"+updatesqlresult10);

						//返回成功结果
						JSONObject  jsonALL3 = new JSONObject();
						jsonALL3.put("retCode", "1");
						jsonALL3.put("retMessage", "订单信息同步成功");
						return jsonALL3;
					}

					else{
						//返回失败结果
						JSONObject  jsonALL3 = new JSONObject();
						jsonALL3.put("retCode", "-1");
						jsonALL3.put("retMessage", "failure");
						jsonALL3.put("workorderid", "");
						return jsonALL3;
					}
				}
			
			}
		
			
			
			if(v_interfacetype=="visit"){//生成回访
				String orderNo = json.getString("orderNo");               //增值服务平台订单号
				
				//更新 realvisiter_flag 以生成回访
				def updatesql1="update objective set realvisiter_flag= 0  where workorderid='"+orderNo+"'";
				def updatesqlresult1=eliteBean.update(updatesql1,"dataSource");
				
				//返回成功结果
				JSONObject  responseJson = new JSONObject();
				responseJson.put("retCode", "1");
				responseJson.put("retMessage", "触发回访成功");
				return responseJson;
			}
		
		
		
			if(v_interfacetype=="evaluate"){//评价
				String orderNo = json.getString("orderNo");               //增值服务平台订单号
				String remark;
				if(json.has("remark")){
					remark  = json.getString("remark");     		//备注
				}else{
					remark="";
				}
				JSONArray evalList=json.getJSONArray("evalList");   //评价信息
				Map<String,String> evalMap = new HashMap<String,String>();
				for(int i=0;i<evalList.size();i++){
					JSONObject eval = evalList.get(i);
					String evaluateTarget = eval.getString("evaluateTarget");
					String score = eval.getString("score");
					evalMap.put(evaluateTarget,score);
				}
				def updateEval="insert into tabcdh_vas_evaluate (evaluate_id, order_no, target_0 ,target_1 ,target_2,target_3, remark,create_time) values(sys_guid(),'"+orderNo+"','"+evalMap.get("0")+"','"+evalMap.get("1")+"','"+evalMap.get("2")+"','"+evalMap.get("3")+"','"+remark+"',to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'))";
				def updateEvalResult=eliteBean.update(updateEval,"dataSource");
				
				 //返回成功结果
				JSONObject  responseJson = new JSONObject();
				responseJson.put("retCode", "1");
				responseJson.put("retMessage", "评价同步成功");
				return responseJson;
				
			}
		}catch(Exception e){
			JSONObject  responseJson = new JSONObject();
			responseJson.put("retCode", "-1");
			responseJson.put("retMessage", e.getMessage());
			return responseJson;
		}
    }
}